import { Camera, Scene, Vector3, WebGLRenderer } from "three";
import type { Stage } from "../components/initScene";
import type { OrbitControls } from "three/examples/jsm/Addons.js";
import { Sky } from "../utils/sky";
import { TileMap, TileSource } from "three-tile";
import * as ttPlugin from "three-tile/plugin";

export function initWind(stage: Stage) {
  stage.loopRender();
  const { scene, camera, controls, renderer } = stage;
  const sky = new Sky();
  sky.scale.setScalar(45000000);
  scene.environment = sky.renderTarget.texture;
  scene.background = sky.renderTarget.texture;
  controls.maxPolarAngle = Math.PI * 0.45;
  controls.screenSpacePanning = false;
  camera.far = 5000000;
  const arcImageSource = new ttPlugin.ArcGisSource();
  const djkimgSource = new TileSource({
    url: "http://192.168.7.102:8887/files/danjiangkou/{z}/{x}/{y}.png",
    maxLevel: 18,
    minLevel: 1,
    format: "png",
    bounds: [
      111.448659896851, 32.519016265869, 111.551742553711, 32.5865650177,
    ],
  });
  const mtImgSource = new TileSource({
    url: "http://192.168.7.102:8887/files//motuo/dom/{z}/{x}/{y}.png",
    maxLevel: 18,
    minLevel: 14,
    format: "png",
    bounds: [
      95.263563428243998, 29.2922832651106688, 95.3846829301718202,
      29.3633229729785086,
    ],
  });
  const mtDemSource = new TileSource({
    url: "http://192.168.7.102:8887/files/motuo/dem/{z}/{x}/{y}.png",
    maxLevel: 15,
    minLevel: 8,
    dataType: "terrain-rgb",
    format: "png",
    bounds: [
      95.263563428243998, 29.2922832651106688, 95.3846829301718202,
      29.3633229729785086,
    ],
  });
  const demSource = new TileSource({
    url: "http://192.168.7.102:8887/files/danjiangkou/dem/{z}/{x}/{y}.png",
    format: "png",
    dataType: "terrain-rgb",
    maxLevel: 14,
    minLevel: 8,
    bounds: [
      111.448659896851, 32.519016265869, 111.551742553711, 32.5865650177,
    ],
  });
  const tileMap = new TileMap({
    imgSource:[djkimgSource,mtImgSource,arcImageSource],
    demSource,
  });
  tileMap.rotateX(-Math.PI / 2);

  scene.add(tileMap);

  const mapflyto = (center: number[], height = 100) => {
    const centerPostion = tileMap.geo2world(
      new Vector3(center[0], center[1], 0)
    );
    // 摄像机经纬度高度（m）转为世界坐标
    const cameraPosition = tileMap.geo2world(
      new Vector3(center[0], center[1], height)
    );
    // 调整摄像机位置
    camera.position.copy(cameraPosition);
    // 调整地图中心位置
    controls.target.copy(centerPostion);
    camera.updateProjectionMatrix();
    controls.update();
  };
  mapflyto([111.489803, 32.556104], 1000);

  console.log(tileMap);

  stage.beforeRender = () => {
    sky.update(renderer);
  };

  return {
    mapflyto,
  };
}
